package com.example.demo.service.impl;

import com.example.demo.entity.Furniture;
import com.example.demo.entity.Order;
import com.example.demo.entity.Users;
import com.example.demo.mapper.ordermapper;
import com.example.demo.service.OrderService;
import com.example.demo.util.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    ordermapper ordermapper;
    @Override
    public Users<Order> orderPage(int page,int size,String query,String username) {
        List<Order> list = ordermapper.list(query,username);
        List<Order> page1 = ordermapper.page(page, size, query,username);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //List<Order> list1=new ArrayList<>();
        for (Order order : page1) {
            order.setCt(dateFormat.format(order.getCreatedTime()));
            order.setMt(dateFormat.format(order.getModifiedTime()));
        }
        Users<Order> users=new Users<>();
        users.setUsers(page1);
        users.setTotal(list);
        return users;
    }

    @Override
    public void delete(int id) {
        int i= ordermapper.delete(id);
        if(i<=0){
            throw new ServiceException("删除失败");
        }
    }

    @Override
    public void add(Furniture furniture, String username) {
        List<Order> list = ordermapper.list(furniture.getName(), username);
        log.info("add"+list.size());
        if (list.size()>0){
            log.info("add"+list.get(0).toString());
            ordermapper.update(list.get(0).getNumber()+1,furniture.getName(),username,new Date());
        }
        else{
            Order order=new Order();
            order.setName(furniture.getName());
            order.setNumber(1);
            order.setPrice(furniture.getPrice());
            order.setCreatedTime(new Date());
            order.setCreatedUser(username);
            order.setModifiedTime(new Date());
            order.setModifiedUser(username);
            ordermapper.add(order);
        }

    }
//if(order.getNumber()==1){
//        ordermapper.delete(order.getId());
//    }
    @Override
    public void update(Order order) {
        ordermapper.update1(1,new Date(),order.getId());
    }

    @Override
    public void update1(Order order) {
        ordermapper.update(order.getNumber()-1, order.getName(), order.getCreatedUser(),new Date());
    }
}
